<template>
    <div>
        <el-page-header icon="" content="个人中心" title="学生学业质量分析系统">
            <el-row>
                <el-col :span="8">
                    <el-card>
                        <el-avatar :size="50" :src="actualAvatar" />
                        <h3>{{ store.user.username }}</h3>
                        <h5>{{ store.user.roleName }}</h5>
                    </el-card>
                </el-col>
                <el-col :span="16">
                    <el-card>
                        <el-form ref="userFormRef" :model="userForm" :rules="rules" label-width="120px" class="userForm"
                            :size="formSize" status-icon>
                            <el-form-item label="用户名" prop="username">
                                <el-input v-model="userForm.username" />
                            </el-form-item>
                            <el-form-item label="密码" prop="password">
                                <el-input v-model="userForm.password" type="password" placeholder="请输入密码"
                                    show-password />
                            </el-form-item>
                            <el-form-item label="性别" prop="gender">
                                <el-select v-model="userForm.gender" placeholder="请选择性别">
                                    <el-option v-for="item in genderOption" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="简介" prop="introduction">
                                <el-input v-model="userForm.introduction" type="textarea" placeholder="请输入简介"
                                    show-password />
                            </el-form-item>
                            <el-form-item label="用户头像" prop="avatarUrl">
                                <candy-image-upload :avatar="userForm.avatarUrl"
                                    @change="handleChange"></candy-image-upload>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="submitForm(userFormRef)">保存</el-button>
                                <el-button @click="resetForm(userFormRef)">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                </el-col>
            </el-row>
        </el-page-header>
    </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import useUserStore from '../../store/useUserStore'
import { ElMessage } from 'element-plus'
import CandyImageUpload from '../../components/center/CandyImageUpload.vue'
import candyUpload from '../../util/CandyUpload'

// 解构出来的属性不具备响应式特点，只能给userForm赋一次值回显用
const { user: { _id, username, gender, introduction, role: { roleName } }, changeUser } = useUserStore()
const store = useUserStore()

const defaultAvatar = new URL('../../assets/avatar.png', import.meta.url).href

const actualAvatar = computed(() => store.user.avatarUrl ? `http://localhost:3000/${store.user.avatarUrl}` : defaultAvatar)

const formSize = ref('default')

const userFormRef = ref('userFormRef')
const userForm = reactive({
    username,
    password: '123456',
    gender,
    introduction,
    file: null,
    avatarUrl: null
})

if (store.user.avatarUrl) {
    userForm.avatarUrl = store.user.avatarUrl
}

const genderOption = [
    {
        label: "保密",
        value: 0
    },
    {
        label: "男",
        value: 1
    },
    {
        label: "女",
        value: 2
    }
]

const handleChange = (file) => {
    userForm.file = file
}

const rules = reactive({
    username: [
        { required: true, message: '用户名不为空！', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '密码不为空！', trigger: 'blur' },
        { min: 3, max: 16, message: '密码长度在3到16个字符之间', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'blur' }
    ],
    introduction: [
        { required: true, message: '请填写简介', trigger: 'blur' }
    ]
})

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                const roleType = store.user.role.roleType
                const res = await candyUpload(`/adminapi/center/${roleType}/${_id}/upload`, userForm)

                const { statusText, data } = res
                if (statusText === 'OK') {
                    changeUser({
                        ...store.user,
                        username: roleType === 3 ? data.studentname : data.username,
                        ...data
                    })
                    ElMessage.success('保存成功！')
                } else {
                    ElMessage.error('保存失败！')
                }
            } catch (error) {
                ElMessage.error('保存失败！')
                console.error(error)
            }
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.el-row {
    margin-top: 20px;

    .el-card {
        text-align: center}
}
</style>